package cn.zyq.ykb.service.user.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.math.MathUtil;
import cn.zyq.ykb.beans.sys.SysAdmin;
import cn.zyq.ykb.beans.task.bo.UserCashAuditBo;
import cn.zyq.ykb.beans.user.User;
import cn.zyq.ykb.beans.user.UserBalance;
import cn.zyq.ykb.beans.user.UserCash;
import cn.zyq.ykb.beans.user.bo.UserBalanceBo;
import cn.zyq.ykb.mapper.user.UserBalanceMapper;
import cn.zyq.ykb.mapper.user.UserCashMapper;
import cn.zyq.ykb.mapper.user.UserMapper;
import cn.zyq.ykb.service.user.UserCashService;
import cn.zyq.ykb.system.common.BaseService;
import cn.zyq.ykb.system.common.PageParam;
import cn.zyq.ykb.system.enums.core.AuditTypeEnum;
import cn.zyq.ykb.system.enums.core.ResponseCodeEnum;
import cn.zyq.ykb.system.enums.core.TaskAuditEnum;
import cn.zyq.ykb.system.enums.core.UserBalanceStatusEnum;
import cn.zyq.ykb.system.exception.BusinessException;
import cn.zyq.ykb.system.pay.core.client.PayClient;
import cn.zyq.ykb.system.pay.core.client.PayCommonResult;
import cn.zyq.ykb.system.pay.core.client.dto.PayOrderTransferReqDTO;
import cn.zyq.ykb.system.pay.core.client.dto.PayOrderTransferRespDTO;
import cn.zyq.ykb.system.pay.core.client.impl.alipay.AlipayPayClientConfig;
import cn.zyq.ykb.system.ry.util.SecurityUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 用户-提现记录Service业务层处理
 *
 * @author SystemAuth
 * @date 2023-05-23
 */
@Service
@Slf4j
public class UserCashServiceImpl  extends BaseService implements UserCashService {

    @Autowired
    private UserCashMapper userCashMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserBalanceMapper userBalanceMapper;


    /**
     * 查询用户-提现记录
     *
     * @param userCashID 用户-提现记录主键
     * @return 用户-提现记录
     */
    @Override
    public UserCash selectUserCashByUserCashID(Integer userCashID) {
        UserCash userCash = userCashMapper.selectByPrimaryKey(userCashID);
        if (userCash.getDeleted() == 1) {
            return null;
        }
        return userCash;
    }

    /**
     * 查询用户-提现记录
     *
     * @param serviceID 业务ID
     * @return 用户-提现记录
     */
    @Override
    public UserCash selectUserCashByServiceID(String serviceID) {
        UserCash param = new UserCash();
        param.setDeleted(0);
        param.setServiceID(serviceID);
        return this.userCashMapper.selectOne(param);
    }

    /**
     * 查询用户-提现记录列表
     *
     * @param pageParam
     * @return 用户-提现记录
     */
    @Override
    public PageInfo<UserBalance> selectUserCashList(PageParam pageParam) {
        PageHelper.startPage(pageParam.getPage(), pageParam.getPageSize());
        pageParam.getKv().put("deleted", 0);
        List<UserBalance> userBalances=this.userBalanceMapper.txListAllGL(pageParam.getKv());
        for (UserBalance userBalance : userBalances) {
            if (!userBalance.getUserID().equals(0)){
                User user = this.userMapper.selectByPrimaryKey(userBalance.getUserID());
                userBalance.setNickName(user.getNickName());
                userBalance.setAvatar(user.getAvatar());
                userBalance.setPosition(user.getPosition());
            }
        }
        return new PageInfo<>(userBalances);
    }

    /**
     * 查询用户-提现记录列表
     * @param param
     * @return 用户-提现记录
     */
    @Override
    public List<UserCash> selectUserCashList(UserCash param) {
        param.setDeleted(0);
        return this.userCashMapper.select(param);
    }
    /**
     * 新增用户-提现记录
     *
     * @param param 用户-提现记录
     * @return 结果
     */
    @Override
    public int insertUserCash(UserCash param) {
        this.setCreateBaseData(param, SecurityUtils.getLoginUser().getSysAdmin());
        return this.userCashMapper.insertSelective(param);
    }

    /**
     * 修改用户-提现记录
     *
     * @param param 用户-提现记录
     * @return 结果
     */
    @Override
    public int updateUserCash(UserCash param) {
        this.setUpdateBaseData(param, SecurityUtils.getLoginUser().getSysAdmin());
        return this.userCashMapper.updateByPrimaryKeySelective(param);
    }

    /**
     * 批量删除用户-提现记录
     *
     * @param userCashIDs 需要删除的用户-提现记录主键
     * @return 结果
     */
    @Override
    public int deleteUserCashByUserCashIDs(Integer[] userCashIDs) {
        int i = 0;
        for (Integer userCashID : userCashIDs) {
            i += this.deleteUserCashByUserCashID(userCashID);
        }
        return i;
    }

    /**
     * 删除用户-提现记录信息
     *
     * @param userCashID 用户-提现记录主键
     * @return 结果
     */
    @Override
    public int deleteUserCashByUserCashID(Integer userCashID) {
        UserCash userCash = this.selectUserCashByUserCashID(userCashID);
        if (userCash == null) {
            return 0;
        } else {
            UserCash storeInfo = new UserCash();
            storeInfo.setUserCashID(userCashID);
            storeInfo.setDeleted(1);
            storeInfo.setUpdateBy(SecurityUtils.getSysAdminID());
            storeInfo.setUpdateTime(LocalDateTime.now());
            this.userCashMapper.updateByPrimaryKeySelective(storeInfo);
            return 1;
        }
    }

    @Transactional
    @Override
    public int audit(UserCashAuditBo bo, SysAdmin loginAdmin, HttpServletRequest request) {

        List<Integer> userCashIDs = bo.getUserCashIDs();
        for (Integer userCashID : userCashIDs) {
            UserCash userCash = this.userCashMapper.selectByPrimaryKey(userCashID);
            if (BeanUtil.isEmpty(userCash)){
                throw new BusinessException(ResponseCodeEnum.ERROR,"该提现申请不存在");
            }
            if (!AuditTypeEnum.AUDITING.getValue().equals(userCash.getState())) {
                throw new BusinessException(ResponseCodeEnum.ERROR, "提现申请已审批，请勿重复提交");
            }
            User user = this.userMapper.selectByPrimaryKey(userCash.getUserID());
            if (bo.getStatus().equals(2)){
                userCash.setState(TaskAuditEnum.SHTG.getValue());

                //新增用户余额变动表
                UserBalance userBalance = new UserBalance();
                userBalance.setUserID(user.getUserID());
                userBalance.setCurrentBalance(user.getWallet().subtract(userCash.getPrice()));
                userBalance.setLastBalance(user.getWallet());
                userBalance.setChangeBalance(userCash.getPrice().negate());
                userBalance.setAssociationID(userCash.getAuditID());
                userBalance.setStatus(UserBalanceStatusEnum.TX.getValue());
                userBalance.setChangeTitle("申请提现");
                this.setCreateBaseData(userBalance,loginAdmin);
                this.userBalanceMapper.insertSelective(userBalance);

                // TODO: 2023/6/2 将钱转到用户提现账号里面

                PayOrderTransferReqDTO dto = new PayOrderTransferReqDTO();
                String userIP = request.getRemoteAddr();
                dto.setUserIp(userIP);
                dto.setNotifyUrl(null);
                dto.setUserAccount(user.getAliAccount());
                dto.setUname(user.getAccountName());
                dto.setOutTradeNo(userCash.getServiceID());
                dto.setTitle("优客帮App提现");
                dto.setAmount(MathUtil.yuanToCent(userCash.getPrice().doubleValue()));
                log.info("组装提现参数 {}",dto);
                PayClient client = AlipayPayClientConfig.getPayClientByChannelId(userCash.getChannelId());
                PayCommonResult<PayOrderTransferRespDTO> result = client.unifiedTransfer(dto);

                log.info("提现结束 {}",result);

            }else if (bo.getStatus().equals(3)){
                userCash.setState(TaskAuditEnum.SHJJ.getValue());
                //将用户钱包金额返回
                user.setWallet(user.getWallet().add(userCash.getPrice()));
                int i = this.userMapper.updateByPrimaryKeySelective(user);
                if (i == 0){
                    throw new BusinessException(ResponseCodeEnum.ERROR,"修改余额失败");
                }

            }else {
                throw new BusinessException(ResponseCodeEnum.ERROR,"没有该状态");
            }
            userCash.setAuditID(loginAdmin.getSysAdminID());
            userCash.setAuditTime(LocalDateTime.now());
            this.setUpdateBaseData(userCash, SecurityUtils.getLoginUser().getSysAdmin());
            int i = this.userCashMapper.updateByPrimaryKeySelective(userCash);
            if (i==0){
                return 0;
            }

        }
        return 1;
    }

    @Override
    public int add(UserBalanceBo bo) {
        UserBalance userBalance = BeanUtil.copyProperties(bo, UserBalance.class);
        userBalance.setStatus(3);
        userBalance.setChangeTitle("申请提现");
        this.setCreateBaseData(userBalance,SecurityUtils.getLoginUser().getSysAdmin());
        return this.userBalanceMapper.insertSelective(userBalance);
    }

    @Override
    public int delete(Integer userBalanceID) {
        return this.userBalanceMapper.deleteByPrimaryKey(userBalanceID);
    }
}
